<template>
  <div class="sparePartList h100">
    <div class="sparePartListTable">
      <listTableNew v-bind="tableSetting" ref="klTable"></listTableNew>
    </div>
    <!-- <div class="sparePartChangeTime">最新同步时间： 2022-03-07 23:34:00</div> -->
    <input
      type="file"
      ref="uploadFile"
      style="display: none"
      accept=".xls, .xlsx"
      :multiple="false"
      @change="autoUploadFile"
    />
  </div>
</template>

<script>
import {
  serchEqBackup, // 分页
  backupImport // 导入
} from "@/api/equipmentLedger/equipmentBackup.js";
export default {
  name: "sparePartList",
  props: {
    arrId: {
      type: Array,
      default: () => {
        return [];
      }
    },
    nodeId: {
      type: String,
      default: ""
    }
  },
  components: {},
  data() {
    return {
      pageType: "list",
      equipmentList: [],
      equipmentListStr: "",
      tableSetting: {
        radioShow: false,
        showCustomBtn: true, //显示自定义列按钮
        showFilterBtn: true, //显示过滤器按钮
        pageConfig: {
          pageCode: "sparePartList", //页面标识，用来存储过滤器以及自定义列的时候用
          userId: this.$store.getters.userInfo.id
        },
        searchObj: {
          searchMethod: (params, sortStr) => {
            this.getTableData(params, sortStr);
          },
          queryData: {
            page: 1,
            pageSize: 15
          },
          searchArr: [
            {
              type: "input",
              label: "备件编号",
              model: "code"
            },
            {
              type: "input",
              label: "备件名称",
              model: "name"
            },
            {
              type: "device",
              label: "适用设备",
              model: "backApply",
              multiple: true,
              methods: arr => {
                let list = [];
                this.equipmentList = [];
                this.equipmentListStr = "";
                if (typeof arr == "object") {
                  if (arr.length) {
                    arr.map(i => {
                      let obj = {
                        equip_id: i.id,
                        equip_name: i.name,
                        level: i.level,
                        parentId: i.parentId,
                        parentName: i.parentName,
                        sort: i.sort,
                        status: i.status
                      };
                      list.push(obj);
                    });
                  }
                  this.equipmentList = list;
                } else {
                  this.equipmentListStr = arr;
                }
              }
            },
            {
              type: "select",
              label: "是否绑定设备",
              model: "isBind",
              option: [
                {
                  label: "是",
                  value: "1"
                },
                {
                  label: "否",
                  value: "0"
                }
              ]
            },
           {
              label: "状态",
              model: "status",
              type: "select",
              // multiple: true,
              option: this.$store.getters["dirtData"]("backup_status")
            },
          ]
        },
        actionList: [
          {
            name: "新建",
            icon: "el-icon-plus",
            content: this.$store.getters["isBtnAuth"]("add")
            ? ""
            : "未授权此功能！",
            disabled:!this.$store.getters["isBtnAuth"]("add"),
            // 点击调用的方法
            method: obj => {
              this.gotoDetails(obj, "sparePartDetails", "add");
            }
          },
          {
            name: "导入",
            icon: "el-icon-refresh-left",
            content: this.$store.getters["isBtnAuth"]("import")
            ? ""
            : "未授权此功能！",
            disabled:!this.$store.getters["isBtnAuth"]("import"),
            method: row => {
              this.uploadFile();
            }
          },
          {
            name: "下载模板",
            icon: "el-icon-download",
            method: obj => {
              this.download();
            }
          },
          {
            name: "批量绑定",
            icon: "el-icon-setting",
            content: this.$store.getters["isBtnAuth"]("bind")
            ? ""
            : "未授权此功能！",
            disabled:!this.$store.getters["isBtnAuth"]("bind"),
            method: row => {
              this.settingBackup();
            }
          }
        ],
        column: [
          {
            label: "备件编号",
            prop: "code",
            sortable: "custom"
          },
          {
            label: "备件名称",
            prop: "name",
            sortable: "custom"
          },
          {
            label: "类别",
            prop: "classifyName",
            sortable: "custom",
            width: "90px"
          },
          {
            label: "备件型号",
            prop: "type",
            sortable: "custom"
          },
          {
            label: "适用设备",
            prop: "backApply",
            sortable: "custom",
            formatter: arr => {
              let str = "";
              str = arr.backApply.map(i => i.equip_name).join(", ");
              return str;
            }
          },
          {
            label: "是否绑定设备",
            prop: "isBind",
            sortable: "custom",
            formatter: row => {
              let value = row.isBind;
              return value == "1" ? "是" : "否";
            },
            width: "140px"
          },
          {
            label: "备件数量",
            prop: "amount",
            sortable: "custom",
            width: "105px"
          },
          {
            label: "计量单位",
            prop: "unit",
            sortable: "custom",
            width: "105px"
          },
          {
            label: "数据来源",
            prop: "origin",
            sortable: "custom",
            formatter: row => {
              let value = row.origin;
              return (
                this.$store.getters["fineDirtDataName"](
                  "backup_origin",
                  value
                ) || value
              );
            },
            width: "105px"
          },
          {
            label: "状态",
            prop: "status",
            sortable: "custom",
            formatter: row => {
              let value = row.status;
              return (
                this.$store.getters["fineDirtDataName"](
                  "backup_status",
                  value
                ) || value
              );
            },
            width: "80px"
          }
        ],
        // 表格数据
        tableData: [],
        //表格方法
        tableMethods: {
          //点击行的方法
          rowClick: row => {
            this.gotoDetails(row, "sparePartDetails", "edit");
          }
        }
      }
    };
  },
  created() {
    /* 添加监听事件 */
    window.addEventListener("storage", this.updateData);
  },
  beforeDestroy() {
    /* 删除监听事件 */
    window.removeEventListener("storage", this.updateData);
  },
  mounted() {
    this.init();
  },
  methods: {
    init() {
      this.$refs.klTable.getTableConfig();
      setTimeout(() => {
        this.updateData();
      }, 1000);
    },
    updateData() {
      this.$refs.klTable.searchData();
      this.$emit("getTreeData");
    },
    getTableData(params, sortStr) {
      let form = { ...params };
      // if(typeof this.equipmentList == 'object'){
      //   form.backApply = this.equipmentList;
      // }else{
      //   form.backApply = [{
      //     equip_name: this.equipmentListStr
      //   }]
      // }
      if (this.equipmentList.length) {
        form.backApply = this.equipmentList;
      } else {
        if (this.equipmentListStr) {
          form.backApply = [
            {
              equip_name: this.equipmentListStr
            }
          ];
        } else {
          delete form.backApply;
        }
      }
      form.classify = this.arrId;
      delete form["undefined"];
      // 删除所选设备字段
      if (sortStr) {
        form.orders = sortStr;
      } else {
        form.orders = [
          {
            column: "createTime",
            asc: false
          }
        ];
      }
      // 调用接口请求数据
      serchEqBackup(form)
        .then(res => {
          let data = res.data.list || [];
          let total = res.total || 0;
          this.$set(this.tableSetting, "tableData", data);
          this.$set(this.tableSetting, "totalNumber", total);
        })
        .catch(e => {
          this.$set(this.tableSetting, "tableData", []);
          this.$set(this.tableSetting, "totalNumber", 0);
        });
    },
    gotoDetails(row, router, type) {
      let form = {
        pageType: type,
        classifyId: this.nodeId
      };
      if (type != "add") {
        form.id = row.id;
        form.status = row.status;
        form.origin = row.origin;
      }
      const { href } = this.$router.resolve({
        name: router,
        query: form
      });
      window.open(href, "_blank");
    },
    //点击选择文件
    uploadFile() {
      const fileObj = this.$refs.uploadFile;
      fileObj.click();
    },
    // 上传选择的文件
    async autoUploadFile(e, file) {
      let normalFile = this.$refs.uploadFile.files[0];
      let classifyId = this.nodeId;
      const formData = new FormData();
      formData.append("file", normalFile);
      backupImport(classifyId, formData)
        .then(res => {
          if (res.code == 200) {
            this.$message.success("导入成功！！！");
            this.updateData();
            this.$refs.uploadFile.files[0] = [];
          }
        })
        .catch(err => {
          err = String(err);
          if (err.charAt(0) == "[") {
            let code = err
              .replace(/\[|]/g, "")
              .split(",")
              .join(",");
            this.$message.error(`导入失败,备件编号${code}已存在！！！`);
          }
          this.updateData();
        });
      e.target.value = "";
    },
    //下载模板
    download() {
      let path = "eam-service-device/equipmentBackup/template";
      this.$utils.downloadFile(null, "备品备件导入模板", path);
    },
    // 批量绑定
    settingBackup() {
      const { href } = this.$router.resolve({
        name: "bindBackupDetails"
      });
      window.open(href, "_blank");
    }
  },
  watch: {
    arrId: {
      handler(val) {
        this.getTableData();
      }
    }
  }
};
</script>

<style lang="less" scoped>
.sparePartList {
  position: relative;
  min-height: 500px;
  .sparePartListTable {
    // height: calc(100% - 25px);
    height: 100%;
    // min-height: 500px;
  }
  .sparePartChangeTime {
    // position: fixed;
    position: absolute;
    height: 25px;
    line-height: 25px;
    bottom: 0px;
    left: 0px;

    // background-color: skyblue;
    // font-size: 18px;
  }
}
</style>